﻿// bikesController.js

bikeFindr.module.controller('bikesController',
    function bikesController($scope, $http, $route, $location) {

        $scope.searchModel = { name: "", category: "All", state: "All" };
        $scope.dataCount = 0;
        $scope.data = [];
        $scope.isBusy = false;
        $scope.searchFailed = false;
        $scope.searchWasEmpty = false;
        $scope.searchWasTooMany = false;
        $scope.html = '<p> raw HTML </p>';


        $scope.totalPages = 0;
        $scope.pageNumber = 1;
        var dataPortion = 20; //controls how many items will be displayed per page

        $scope.search = function (searchModel, pageNumber) {

            $scope.isBusy = true;

            $http.get("/api/bikes?name=" + searchModel.name + "&category=" + searchModel.category + "&state=" + searchModel.state + "&pageNumber=" + pageNumber)
                .then(function(result) {
                    angular.copy(result.data.Bikes, $scope.data);
                    $scope.dataCount = result.data.NumberOfItemsFound;
                    $scope.searchFailed = false;
                    $scope.searchWasEmpty = false;
                    $scope.searchWasTooMany = false;

                    if ($scope.dataCount === 0)
                    {
                        $scope.searchWasEmpty = true;
                    }
                    else {
                        $scope.totalPages = Math.ceil($scope.dataCount / dataPortion);

                        if ($scope.dataCount === 100) {
                            $scope.searchWasTooMany = true;
                        }
                    }
                },
                    function() {
                        //error
                        $scope.isBusy = false;
                        $scope.searchFailed = true;
                    })
                .then(function() {
                    $scope.isBusy = false;
                    
                   
                });
         };

        $scope.selectPage = function(pageNumber) {
            $scope.search($scope.searchModel, pageNumber);
            $scope.pageNumber = pageNumber;
             window.scrollTo(0, 0);
    
        };


        $scope.fancybox = function(href) {
            var elem = $('#'+href);
            elem.fancybox().trigger('click');
         };


        $scope.reload = function() {
            $route.reload();
        };

        $scope.getNavLinkClass = function(path) {
            if ($location.path() === path) {
                return "active";
            } else {
                return "";
            }
        };

 });